﻿namespace TwiMixer.Handlers
{
    using System;
    using System.Text.RegularExpressions;
    using System.Web;
    using TwiMixer.RESTAPI;

    /// <summary>
    /// oauth认证直接对http请求进行转发
    /// 需要客户端支持自定义签名url
    /// chromebrid(自定义)和twigee(固定官方地址)支持
    /// </summary>
    public class RestOAuthHandler : IHttpHandler
    {
        /// <summary>
        /// 重用
        /// </summary>
        public bool IsReusable
        {
            get { return true; }
        }

        #region
        /* 
            //旧方案oauth代码 直接转发 processrequest（）
            string requestUrl = "https://api.twitter.com";
            requestUrl += context.Request.Path;
            requestUrl += context.Request.Url.Query;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);//WebRequest.Create(context.Request.Url);

            request.ContentType = context.Request.ContentType;
            request.Method = context.Request.HttpMethod;
            request.ServicePoint.Expect100Continue = false;
            request.UserAgent = context.Request.UserAgent;

            switch (request.Method)
            {
                case "GET":
                    break;
                case "POST":
                    string contentBody =  new StreamReader(context.Request.InputStream).ReadToEnd();
                    request.ContentLength = contentBody.Length;
                    StreamWriter writer = new StreamWriter(request.GetRequestStream());

                    writer.Write(contentBody);
                    writer.Close();
                    break;
                default:
                    break;
            }
             
            StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream());

            context.Response.Write(reader.ReadToEnd()); 
            */

        #endregion

        /// <summary>
        /// oauth 的处理 支持自定义oauth url的客户端使用
        /// </summary>
        /// <param name="context">httpcontext</param>
        public void ProcessRequest(HttpContext context)
        {
            string responseBody;
            string[] path = context.Request.Path.Split('/');

            // 获取path中的api类型以及oauth方法 例:oauth/sina/request_token
            string providerName = path[3];
            string oauthMethod = path[4];

            // 创建api访问对象
            APIProviderEnum api = (APIProviderEnum)Enum.Parse(typeof(APIProviderEnum), providerName);
            APIProvider provider = (APIProvider)APIProviderFactory.GetApiProvider(api);

            // 对oauth不同方法进行处理
            switch (oauthMethod)
            {
                case "request_token":
                    // 传递callbackurl到http请求中
                    // 当callback没有值时将其设置为oob
                    string oauth_callback = context.Request.Params["oauth_callback"];
                    if (oauth_callback == null)
                    {
                        oauth_callback = "oob";
                    }

                    responseBody = provider.OAuthRequestToken(oauth_callback);

                    // 保存request_token返回的token和token_secret
                    context.Response.Cookies["sina"].Value = responseBody;
                    context.Response.Write(responseBody);
                    break;

                case "authorize":
                    // 重定向地址 让用户完成授权
                    context.Response.Redirect(provider.OAuthAuthorize(context.Request.Params["oauth_token"]));
                    break;

                case "access_token":
                    // 读取之前保存的token和token_secret
                    // 完成交换access_token步骤
                    string responseToken = context.Request.Cookies["sina"].Value;
                    string oauth_token = Regex.Match(responseToken, "oauth_token=([^&]+)").Groups[1].Value;
                    string oauth_token_secret = Regex.Match(responseToken, "oauth_token_secret=([^&]+)").Groups[1].Value;
                    responseBody = provider.OAuthAccessToken(oauth_token, oauth_token_secret, context.Request.Params["oauth_verifier"]);

                    // 保存用户的token和token_secret
                    // 并返回给客户端,这个保存的token用来以后的签名计算
                    Utility.SaveUserToken(responseBody, provider.ApiProviderType.ToString());
                    context.Response.Write(responseBody);
                    break;
                default:
                    break;
            }

            context.Response.End();
        }
    }
}